/*************************************************************************
    > File Name: get_addr.c
    > Author: bw
    > Mail: wang_biao@126.com 
    > Created Time: 2024年01月25日 星期四 17时25分03秒
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>  
#include <sys/socket.h>  
#include <netdb.h> 

#include <arpa/inet.h>

int main(int argc, char *argv[])
{
	
	 struct addrinfo hints, *res, *rp;  
	int status;  
	  char ipstr[INET6_ADDRSTRLEN];  
	   
	  if (argc != 2) {  
		         fprintf(stderr, "Usage: %s <domain>\n", argv[0]);  
		         exit(EXIT_FAILURE);  
	 }  
	   
	 memset(&hints, 0, sizeof hints);  
	 hints.ai_family = AF_INET; // AF_INET or AF_INET6 to force version  
	 hints.ai_socktype = SOCK_STREAM;  
				   
	 if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {  
	     fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));  
	     exit(EXIT_FAILURE);  
	 }  
		
	for(rp = res; rp != NULL; rp = rp->ai_next) {
		void *addr;
		char ipstr[128];

		if(rp->ai_family==AF_INET) {
			struct sockaddr_in *ipv4 = (struct sockaddr_in*) rp->ai_addr;
			addr = &(ipv4->sin_addr);
		}

		// 将 addr 转换成 字符串格式的地址
		inet_ntop(AF_INET, addr, ipstr, sizeof(ipstr));
	
		printf("IP addr: %s\n", ipstr);
	}

//	 printf("IP address for %s is %s\n", argv[1], res->ai_addr->sa_data);  

	freeaddrinfo(res); // No longer needed  
									   
	return 0;
}
